﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using QMSDAL;

namespace QuaManSys.OuterInfo
{
    public partial class OuterInfoRegistA : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurUser"] == null)
            {
                Response.Redirect("~/Login.aspx");
            }
            lblQuaInfoProNo.Text = getOutQuaInfo();
            fdbktime.Attributes.Add("ReadOnly", "True");
            lblCusRT.Attributes.Add("ReadOnly", "True");
            txtProDL.Attributes.Add("ReadOnly", "True");
            txtKeyWords.Attributes.Add("ReadOnly", "True");

            if (!IsPostBack)
            {
                initddlProNo();         //工程编号下拉框
                initResponDept();
                initRelatedDept();

                ProcssComd.SelectedIndex = 0;
                CareLevel.SelectedIndex = 0;
                CustmReq.SelectedIndex = 0;
                InfoCls.SelectedIndex = 0;

            }
            txtlblMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
            txtlblMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            //从session中取出当前用户信息并显示
            CurUser user = (CurUser)Session["CurUser"];
            //判断当前用户是否具有归档权限
            bool roleAccess = Permission.JudgePermission(user, "2A", "A");
            if (roleAccess)
            {
                if (isValidate())
                {
                    fileUpload();
                    insertQualityInfo();
                    insertQuaFeedback();
                    insertResponsDept();
                    Common.OuterRelatedDeptOperation.AddOuterRelatedDept(lblQuaInfoProNo.Text, user.department);
                    Response.Redirect("SubmitSuccess.aspx");
                }
                else
                {
                    Response.Redirect("OuterInfoRegist.aspx");
                }
            }
            else
            {
                Response.Write("<script>alert('你没有提交的权限')</script>");
            }

        }

        protected void ddlProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string projNo = ddlProNo.Text;
            txtlblMacTyp.Text = GCBH.GetJXGCBH(projNo);
            txtlblMacNo.Text = GCBH.GetTFGCBH(projNo);
        }

        /*
         * multiView的下一步
         */
        protected void nextstep_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 1;
        }

        /*
         * multiView的上一步
         */
        protected void prestep_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 0;
        }

        #region
        public string maxID()
        {
            var context = new QuaManSysEntities();

            if (context.OuterQualityInfo.Count() != 0)
            {
                var query = from b in context.OuterQualityInfo
                            orderby b.qualityInfoId
                            select b.qualityInfoId;
                return query.Max();
            }
            return "";
        }

        /*
         * 返回外部质量信息号
         */
        private string getOutQuaInfo()
        {
            string ret = "CQI" + "DEPART";                   //TODO: to be fixed, "dept" should replaced with real dept
            string maxid = maxID();
            string dbDateTime = DateTime.Now.Year.ToString();
            if (maxid == "") return ret += dbDateTime + "001";
            string year = maxid.Substring(9, 4);

            if (year != dbDateTime)
            {
                ret += dbDateTime + "001";
            }
            else
            {
                string id = maxid.Substring(13, 3);
                ret += year + (Convert.ToInt16(id) + 1).ToString("000");
            }
            return ret;
        }


        /// <summary>
        /// 初始化工程编号下拉框
        /// </summary>

        private void initddlProNo()
        {
            DataSet myDs = GCBH.GetAllProjectNumbers();
            foreach (DataTable dt in myDs.Tables)
            {
                ddlProNo.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        ddlProNo.Items.Insert(count++, li);
                    }
                }
            }
            txtlblMacTyp.Text = GCBH.GetJXGCBH(ddlProNo.Text);
            txtlblMacNo.Text = GCBH.GetTFGCBH(ddlProNo.Text);
        }



        /// <summary>
        /// 写质量信息到质量信息表中
        /// </summary>
        private void insertQualityInfo()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                string infoCategory = InfoCls.SelectedIndex.ToString();
                CurUser user = (CurUser)Session["CurUser"];
                OuterQualityInfo outInfo = new OuterQualityInfo
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    projectNo = ddlProNo.Text,
                    components = txtComponent.Text,
                    producer = txtManufac.Text,
                    faultType = txtFaiTyp.Text,
                    projectCategory = txtPjCls.Text,
                    name = txtPjNam.Text,
                    deadline = Convert.ToDateTime(txtProDL.Text),
                    informationCategory = infoCategory,
                    informationSource = txtSearch.Text,
                    levelOfImportance = txtImpLev.Text,
                    description = txtInfoDsc.Text,
                    recommendedTreatPlan = txtReqAdv.Text,
                    processingStatus = "分发",
                    processingResults = txtReqRsl.Text,
                    processingAssess = txtProCmm.Text,
                    registerName = user.employeeId
                };
                context.OuterQualityInfo.Add(outInfo);
                context.SaveChanges();
            }
        }

        /// <summary>
        /// 写反馈表到数据库的反馈表中
        /// </summary>
        private void insertQuaFeedback()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                string subsquReq = CustmReq.SelectedIndex.ToString();
                if (CustmReq.SelectedIndex == 3)
                    subsquReq += "|" + instruction.Text;
                OuterQualityInfoFeedback OutQuaFdbck = new OuterQualityInfoFeedback
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    feedbackUnit = lblFdCom.Text,
                    feedbackName = txtFdPer.Text,
                    feedbackTime = Convert.ToDateTime(fdbktime.Text),
                    customerCompany = lblCusCo.Text,
                    relatedParty = lblRelCo.Text,
                    customerName = lblCusNam.Text,
                    customerRole = lblCusRol.Text,
                    customerPhone = lblCusTel.Text,
                    customerReqCloTime = Convert.ToDateTime(lblCusRT.Text),
                    customerAttitude = CareLevel.SelectedIndex.ToString(),
                    cusomerOtherInfo = TextBox4.Text,
                    qualityInfoDes = TextBox2.Text,
                    solutionProposal = TextBox3.Text,
                    subsequentRequest = subsquReq,
                    processingDemands = ProcssComd.SelectedIndex.ToString()
                };

                context.OuterQualityInfoFeedback.Add(OutQuaFdbck);
                context.SaveChanges();

            }
        }

        /// <summary>
        /// 写责任部门和关注部门到数据库中
        /// </summary>
        private void insertResponsDept()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                OuterResponsibleDepart respons = new OuterResponsibleDepart
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    isResponDepart = 1,
                    department = ResponDept.Text
                };

                context.OuterResponsibleDepart.Add(respons);
                context.SaveChanges();

                string focString = txtKeyWords.Text;
                if (focString == "") return;//fixed
                string[] focDept = focString.Split('|');

                for (int i = 0; i < focDept.Length; i++)
                {
                    OuterResponsibleDepart focusDept = new OuterResponsibleDepart
                    {
                        qualityInfoId = lblQuaInfoProNo.Text,
                        isResponDepart = 0,
                        department = focDept[i]
                    };
                    context.OuterResponsibleDepart.Add(focusDept);
                    context.SaveChanges();
                }

            }
        }
        #endregion

        bool isValidate()
        {
            if (fdbktime.Text == "") return false;
            if (lblCusRT.Text == "") return false;
            if (txtProDL.Text == "") return false;

            return true;
        }


        protected void ResponDept_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                cblKeyWords.Items.Clear();

                if (txtKeyWords.Text != "")
                {
                    string newRealtedStr = "";
                    string[] listStr = txtKeyWords.Text.Split('|');
                    for (int i = 0, k = 0; i < listStr.Length; i++)
                    {
                        if (listStr[i] == ResponDept.Text) continue;
                        if (k++ == 0)
                        {
                            newRealtedStr += listStr[i];
                        }
                        else
                        {
                            newRealtedStr += "|" + listStr[i];
                        }
                    }
                    txtKeyWords.Text = newRealtedStr;
                }
                int count = 0;
                string[] list = txtKeyWords.Text.Split('|');

                DataSet ds = Department.GetAllDept();
                foreach (DataTable dt in ds.Tables)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                        {
                            ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                            if (list.Contains(dt.Rows[curRow][curCol].ToString())) li.Selected = true;
                            if (!dt.Rows[curRow][curCol].ToString().Equals(ResponDept.Text))
                                cblKeyWords.Items.Insert(count++, li);
                        }
                    }
                }
            }
            catch (EntitySqlException ex)
            {
                Response.Write("<script>alert('" + ex.ToString() + "')</script>");
            }

        }

        private void initResponDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                ResponDept.Items.Clear();
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        if (dt.Rows[curRow][curCol].ToString() == ResponDept.Text) continue;
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        ResponDept.Items.Insert(count++, li);
                    }
                }
            }
        }

        /*
         * 初始化关注部门复选框选项                  
         */
        private void initRelatedDept()
        {
            DataSet ds = Department.GetAllDept();
            foreach (DataTable dt in ds.Tables)
            {
                cblKeyWords.Items.Clear();
                string[] listStr = txtKeyWords.Text.Split('|');
                int count = 0;
                for (int curCol = 0; curCol < dt.Columns.Count; curCol++)
                {
                    for (int curRow = 0; curRow < dt.Rows.Count; curRow++)
                    {
                        if (dt.Rows[curRow][curCol].ToString() == ResponDept.Text) continue;
                        ListItem li = new ListItem(dt.Rows[curRow][curCol].ToString());
                        if (listStr.Contains(dt.Rows[curRow][curCol].ToString())) li.Selected = true;
                        cblKeyWords.Items.Insert(count++, li);
                    }
                }
            }
        }

        #region 文件上传
        protected void fileUpload()
        {
            #region
            int cnt = Convert.ToInt16(hidden.Value.ToString());
            HtmlInputFile f = this.FileUploadD1;
            UpLoadFile(f.PostedFile);

            for (int i = 2; i <= cnt; i++)
            {
                HttpPostedFile f1 = Request.Files["FileUploadD" + i];
                UpLoadFile(f1);
            }
            #endregion

        }

        /// <summary>
        /// 文件上传。
        /// </summary>
        /// <param name="InputFile"></param>
        /// <param name="Path"></param>
        public string UpLoadFile(HttpPostedFile InputFile)
        {

            //判断有控件内容进入
            string b = "";
            string xdd = "";
            try
            {
                xdd = InputFile.FileName.ToString();//获取上传文件的名字
            }
            catch (Exception e)
            {
                return xdd;
            }
            if (xdd != "")
            {
                string path = "~/FileUploadCS/" + lblQuaInfoProNo.Text + "/";

                string PRICE_FJ_FJMC = "";
                string PRICE_FJ_FJHZ = "";
                string PRICE_FJ_PATH_SC = "";
                string PRICE_FJ_PATH_XZ = "";

                PRICE_FJ_PATH_XZ = path;
                //上传全路径包括文件名G:\\新建文件夹 (4)\\新建 文本文档.txt
                PRICE_FJ_PATH_SC = InputFile.FileName;
                //文件名包括后缀 新建 文本文档.txt"
                PRICE_FJ_FJMC = PRICE_FJ_PATH_SC.Substring(PRICE_FJ_PATH_SC.LastIndexOf("\\") + 1);
                ////
                //建立上传对象
                //
                HttpPostedFile postedFile = InputFile;
                //文件名包括后缀 新建 文本文档.txt"
                string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                //文件后缀
                PRICE_FJ_FJHZ = System.IO.Path.GetExtension(fileName);


                string phyPath = HttpContext.Current.Request.MapPath(PRICE_FJ_PATH_XZ);//获取文件所在根目录
                //判断路径是否存在,若不存在则创建路径
                DirectoryInfo upDir = new DirectoryInfo(phyPath);
                if (!upDir.Exists)
                {
                    upDir.Create();
                }
                //
                //保存文件
                //
                try
                {
                    postedFile.SaveAs(phyPath + PRICE_FJ_FJMC);//文件保存
                    return b = phyPath;

                }
                catch
                {
                    throw new ApplicationException("上传失败!");
                }
                //返回上传文件的信息
            }

            return b;
        }

        #endregion
    }
}